package http

import (
	"context"
	"log"
	"time"
	pbCity "wire/api/city"
	pbUser "wire/api/user"

	"gitee.com/go-mod/framework/api"
	"gitee.com/go-mod/framework/config"
	"github.com/go-resty/resty/v2"
)

type Client struct {
	ctx context.Context
}

func NewClient() *Client {
	return &Client{
		ctx: context.Background(),
	}
}

func (c *Client) request(method string, uri string, body interface{}, result interface{}) {
	addr := config.GetString("http-client.addr")
	//retry := 1
	r := resty.New().SetRetryWaitTime(500 * time.Millisecond) //.SetRetryCount(retry)
	switch method {
	case "get":
		_, err := r.R().ForceContentType("application/json").SetBody(body).SetResult(result).Get(addr + uri)
		if err != nil {
			log.Printf("resty GET request err: %+v\n", err)
		}
	case "post":
		_, err := r.R().SetHeader("Content-Type", "application/json").ForceContentType("application/json").SetBody(body).SetResult(result).Post(addr + uri)
		if err != nil {
			log.Printf("resty POST request err: %+v\n", err)
		}
	default:
	}
}

type UserGetReply struct {
	api.ApiReply
	Data *pbUser.UserInfo `json:"data"`
}

func (c *Client) UserGet(req *pbUser.GetRequest) (*UserGetReply, error) {
	result := &UserGetReply{}
	c.request("get", "v1/user/get", req, result)
	return result, nil
}

type CityAllReply struct {
	api.ApiReply
	Data *pbCity.AllReply `json:"data"`
}

func (c *Client) CityAll(req *pbCity.AllRequest) (*CityAllReply, error) {
	result := &CityAllReply{}
	c.request("get", "v1/city/all", req, result)
	return result, nil
}
